package com.cskaoyan.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author stone
 * @date 2022/03/22 16:21
 */
@Component
@Aspect //增加Aspect之后@Component不要省略掉
public class CustomAspect {

    //id:以方法名作为id
    //expression：以@Pointcut的value属性值作为表达式
    @Pointcut("@annotation(com.cskaoyan.anno.SayHello)")
    public void servicePointcut() {
    }

    //@Before("servicePointcut()")
    @Before("execution(* com..service..*(..))")
    public void hello() {//before通知方法
        System.out.println("before");
    }
    @After("servicePointcut()")
    public void world() {//after通知方法
        System.out.println("after");
    }

    @Around("servicePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("around前半部分");
        //委托类方法
        Object proceed = joinPoint.proceed();//类似于method.invoke 、methodInvocation.proceed
        System.out.println("around后半部分");
        return proceed + "?";//返回值作为代理对象的执行结果
    }

    @AfterReturning(value = "servicePointcut()",returning = "result")
    //可以拿到委托类方法的执行结果
    public void afterReturning(Object result) {
        System.out.println("afterReturning" + result);
    }

    @AfterThrowing(value = "servicePointcut()",throwing = "exception")
    //可以获得抛出的异常对象
    public void afterThrowing(Exception exception) {
        System.out.println("抛出异常：" + exception.getMessage());

    }
}
